package com.zuipin.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.esms.common.entity.Account;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zuipin.entity.BalanceRecord;
import com.zuipin.entity.BaseDictionaryData;
import com.zuipin.entity.DeliveryAddress;
import com.zuipin.entity.GrowthValRecord;
import com.zuipin.entity.IntegralRecord;
import com.zuipin.entity.Member;
import com.zuipin.entity.MemberAccount;
import com.zuipin.entity.MemberLevel;
import com.zuipin.enums.BalanceType;
import com.zuipin.enums.GrowthValType;
import com.zuipin.enums.IntegralOrBalance;
import com.zuipin.enums.IntegralType;
import com.zuipin.enums.MemberStatus;
import com.zuipin.framework.emuns.ErrorCode;
import com.zuipin.framework.exception.CustomException;
import com.zuipin.framework.result.PageResult;
import com.zuipin.framework.result.Result;
import com.zuipin.mapper.DeliveryAddressMapper;
import com.zuipin.mapper.GrowthValRecordMapper;
import com.zuipin.mapper.MemberAccountMapper;
import com.zuipin.mapper.MemberLevelMapper;
import com.zuipin.mapper.MemberMapper;
import com.zuipin.service.IBalanceRecordService;
import com.zuipin.service.IBaseDictionaryDataService;
import com.zuipin.service.IIntegralRecordService;
import com.zuipin.service.IMemberAccountService;
import com.zuipin.service.IMemberService;
import com.zuipin.util.ConstantsUtil;
import com.zuipin.util.DateUtils;
import com.zuipin.util.Pagination;
import com.zuipin.util.RedisUtils;
import com.zuipin.util.RegexUtils;
import com.zuipin.util.SmsSendUtil;
import com.zuipin.util.StringUtil;
import com.zuipin.vo.BackDeliveryAddressVo;
import com.zuipin.vo.BackMemberDetailVo;
import com.zuipin.vo.BackMemberVo;
import com.zuipin.vo.BaseDictionaryDataVo;
import com.zuipin.vo.MemberSearchVo;

/**
 * @ClassName: MemberServiceImpl
 * @author wuyicheng
 * @time 2017年3月23日下午2:38:37
 */
@Service
public class MemberServiceImpl implements IMemberService {
	
	private static Logger				log				= LoggerFactory.getLogger(MemberServiceImpl.class);
	@Resource
	private MemberMapper				memberMapper;
	@Resource
	private DeliveryAddressMapper		deliveryAddressMapper;
	@Resource
	private MemberAccountMapper			memberAccountMapper;
	@Resource
	private MemberLevelMapper			memberLevelMapper;
	@Resource
	private IBalanceRecordService		balanceRecordService;
	@Resource
	private IIntegralRecordService		integralRecordService;
	@Resource
	private GrowthValRecordMapper		growthValRecordMapper;
	
	@Autowired
	private IMemberAccountService		memberAccountService;
	
	@Resource
	private RedisUtils					redisUtils;
	private final static String			TYPE			= "_login";
	private final static Integer		MAX_SEND		= 20;
	private final static Integer		NEGATIVE_NUMBER	= -1;
	
	@Resource
	private IBaseDictionaryDataService	baseDictionaryDataService;
	
	/**
	 * 根据ID查找会员信息
	 * 
	 * @Title: findById
	 * @author: wuyicheng
	 * @date: 2017年3月27日上午11:42:32
	 * @param id
	 * @return
	 * @throws
	 */
	@Override
	public Member findById(Long id) {
		if (id == null) {
			return null;
		}
		return memberMapper.findById(id);
	}
	
	/**
	 * 根据手机号查找
	 * 
	 * @Title: findByPhone
	 * @author: wuyicheng
	 * @date: 2017年3月27日上午11:20:19
	 * @param phone
	 * @return
	 * @throws
	 */
	@Override
	public Member findByMember(Member member) {
		if (member != null) {
			return memberMapper.findByMember(member);
		}
		return null;
	}
	
	/**
	 * @Title: findList
	 * @author: wuyicheng
	 * @date: 2017年3月27日下午2:20:51
	 * @param member
	 * @return
	 * @throws
	 */
	@Override
	public List<Member> findList(Member member) {
		if (member != null) {
			
		}
		return null;
	}
	
	/**
	 * 新增一个会员信息
	 * 
	 * @Title: insert
	 * @author: wuyicheng
	 * @date: 2017年3月27日下午2:21:01
	 * @param member
	 * @throws
	 */
	@Override
	public void insert(Member member) {
		if (member != null) {
			String time = DateUtils.getCurrentDateTime();
			member.setCreateTime(time);
			member.setUpdateTime(time);
			member.setFirstLoginTime(time);
			member.setDelFlag(ConstantsUtil.DEL_FLAG_NO_0);
			memberMapper.insert(member);
		}
	}
	
	/**
	 * 更新会员信息
	 * 
	 * @Title: update
	 * @author: wuyicheng
	 * @date: 2017年3月27日下午2:21:49
	 * @param member
	 * @throws
	 */
	@Override
	public void update(Member member) {
		if (member != null) {
			member.setUpdateTime(DateUtils.getCurrentDateTime());
			memberMapper.update(member);
		}
	}
	
	/**
	 * 没有判断空的更新
	 *
	 * @Title: updateByPrimaryKey 
	 * @author: wuyicheng
	 * @date: 2017年6月27日上午10:25:24 
	 * @param member
	 * @throws
	 */
	@Override
	public void updateByPrimaryKey(Member member) {
		if (member != null) {
			member.setUpdateTime(DateUtils.getCurrentDateTime());
			memberMapper.updateByPrimaryKey(member);
		}
	}
	
	/** 
	 *
	 * @Title: deleteById 
	 * @author: wuyicheng
	 * @date: 2017年4月18日下午5:56:08 
	 * @param id
	 * @throws 
	 */
	@Override
	public void deleteById(Long id) {
		Member member = new Member();
		member.setDelFlag(ConstantsUtil.DEL_FLAG_YES_1);
		update(member);
		
	}
	
	/**
	 * @throws ParseException  
	 *	发送短信
	 *
	 * @Title: sendMobileCode 
	 * @author: wuyicheng
	 * @date: 2017年4月24日下午6:45:49 
	 * @param mobilePhone
	 * @param smsAccount
	 * @param smsPassword
	 * @param sendFlag
	 * @param result
	 * @return
	 * @throws 
	 */
	@Override
	public Result<Map<String, Object>> sendMobileCode(String mobilePhone, String smsAccount, String smsPassword, String sendFlag, Result<Map<String, Object>> result,
			String sendType, Long sysId) throws ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		
		if (StringUtil.isNotBlank(mobilePhone)) {
			mobilePhone = mobilePhone.trim();
			// 判断手机号是否为黑名单中
			BaseDictionaryData bdData = new BaseDictionaryData();
			bdData.setDataSimpleName(mobilePhone);
			bdData.setDictionaryId(15L);
			List<BaseDictionaryDataVo> list = baseDictionaryDataService.seachBaseDictionaryData(bdData, null);
			if (list != null && list.size() > 0) {
				result.setErrorCode(ErrorCode.MEMBER_IS_FREEZE);
				result.setMessage(ErrorCode.MEMBER_IS_FREEZE.getCnMessage());
				result.setData(null);
				return result;
			}
			Random random = new Random();
			Integer sendCode = null;
			if (!StringUtil.isNotBlank(sendType)) {
				sendType = TYPE;
			}
			if (redisUtils.exists(mobilePhone + sendType)) {
				String sendCodeStr = redisUtils.get(mobilePhone + sendType);
				if (sendCodeStr != null) {
					sendCode = Integer.parseInt(sendCodeStr);
				}
			}
			// 判断会员是否被冻结
			Member member = findByLoginName(mobilePhone);
			if (member != null) {
				MemberAccount userAccount = new MemberAccount();
				userAccount.setMemberId(member.getId());
				userAccount.setSysId(sysId);
				userAccount = memberAccountMapper.findMemberAccount(userAccount);
				if (userAccount != null) {
					if (memberAccountService.filterMemberStatus(userAccount, result)) {
						return result;
					}
				}
			}
			if (sendCode == null) {
				// 判断一天的发送数量是否到达限制
				Integer sendNum = 0;
				String sendNumStr = null;
				if (redisUtils.exists(mobilePhone)) {
					sendNumStr = redisUtils.get(mobilePhone);
					if (sendNumStr != null && !"".equals(sendNumStr.trim())) {
						sendNum = Integer.parseInt(sendNumStr);
					}
				}
				if (sendNum >= MAX_SEND) {
					result.setErrorCode(ErrorCode.ELSE);
					result.setMessage("今天发送次数已达上限");
					result.setData(null);
					return result;
				}
				sendCode = random.nextInt(8999) + 1000;
				String concat = "验证码：" + sendCode + ",验证码5分钟内输入有效!";
				boolean sendResult = SmsSendUtil.doSendSms(mobilePhone.trim(), concat, new Account(smsAccount, smsPassword), sendFlag);// 发短信
				if (sendResult) {
					redisUtils.set(mobilePhone + sendType, sendCode.toString(), 30L);// 30秒
				}
				sendNumStr = (sendNum + 1) + "";
				// 记录当天的发送次数
				redisUtils.set(mobilePhone, sendNumStr, 24L * 60 * 60);// 24小时
			}
			map.put(ConstantsUtil.SMS_CODE, sendCode);
			result.setErrorCode(ErrorCode.SUCCESS);
			result.setData(map);
		} else {
			result.setErrorCode(ErrorCode.NULL_POINT);
			result.setMessage("mobilePhone is null");
			result.setData(null);
		}
		return result;
	}
	
	/**
	 * 根据登录名查询会员
	 *
	 * @Title: findByLoginName 
	 * @author: wuyicheng
	 * @date: 2017年5月2日下午8:08:42 
	 * @param loginName
	 * @return
	 * @return: Member
	 * @throws
	 */
	@Override
	public Member findByLoginName(String loginName) {
		Member member = new Member();
		// 因为旧数据已处理，不会处在phone和email账号一致的情况
		// 优化如下
		// 判断登录名如果是手机，使用手机登录
		// 否则使用邮箱登录
		if (StringUtil.isNotBlank(loginName) && RegexUtils.isMobileFuzzy(loginName)) {
			member.setPhone(loginName);
		} else {
			member.setEmail(loginName);
		}
		// member.setMemberAccount(loginName);
		return findByMember(member);
	}
	
	@Override
	public List<Member> findListMember(List<Long> ids) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("ids", ids);
		List<Member> memberList = memberMapper.findListMember(map);
		return memberList;
	}
	
	/**
	 * (后台)查询全部会员信息(可模糊查询)
	 * @param sysId
	 * @param search（注意：等级ＩＤ是多选的）
	 * @param page
	 * @return
	 */
	@Override
	public PageResult<List<BackMemberVo>> searchMemberAllByBack(Long sysId, MemberSearchVo search, Pagination page) {
		PageResult<List<BackMemberVo>> result = new PageResult<List<BackMemberVo>>();
		PageHelper.startPage(page.getPageNumber(), page.getPageSize());
		List<String> memberLevelIds = StringUtil.splitString(search.getMemberLevelIds());
		List<BackMemberVo> backMemberVos = memberMapper.findListMemberBack(sysId, search, memberLevelIds);
		PageInfo<BackMemberVo> pageInfo = new PageInfo<>(backMemberVos);
		result.setData(backMemberVos);
		result.setTotal_record(Integer.valueOf(pageInfo.getTotal() + ""));
		result.setErrorCode(ErrorCode.SUCCESS);
		return result;
	}
	
	/**
	 * （后台）查询详细会员详情
	 * @param memberId
	 * @param sysId
	 * @return
	 */
	@Override
	public Result<BackMemberDetailVo> searchMemberByIdBack(Long memberId, Long sysId) {
		Result<BackMemberDetailVo> result = new Result<BackMemberDetailVo>();
		BackMemberDetailVo backMemberDetailVo = memberMapper.findMemberBackById(memberId, sysId);
		if (backMemberDetailVo != null) {
			List<BackDeliveryAddressVo> backDeliveryAddressVos = deliveryAddressMapper.findListByMemberIdAndSysIdBack(memberId, sysId);
			backMemberDetailVo.setBackDeliveryAddressVo(backDeliveryAddressVos);
			result.setData(backMemberDetailVo);
			result.setErrorCode(ErrorCode.SUCCESS);
		} else {
			result.setErrorCode(ErrorCode.NOT_FIND);
		}
		return result;
	}
	
	/**
	 * （后台）修改会员信息－修改会员基本信息、会员等级、会员收货地址
	 * @param backMemberDetailVo
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public Result modityMemberInformation(BackMemberDetailVo backMemberDetailVo) throws CustomException {
		/*memberId- 会员id【会员表】	memberLevelId- 会员等级id【会员账户表】
		  nickName- 昵称【会员表】		lever- 级别【等级表】
		  phone- 绑定手机【会员表】		memberLevelName- 会员等级名称【等级表】
		  email- 邮箱【会员表】			registerTime- 注册时间【会员账户表】（无法修改）
		  							status-  状态【会员账户表】 （无法修改）
									growthValue- 成长值【会员账户表】（无法修改）
									totalIntegral- 会员积分【会员账户表】	（无法修改）
									cumulativeConsume- 消费总额【会员账户表】（无法修改）
									totalAmount- 账户余额【会员账户表】（无法修改）
									sysId- 系统ID【会员账户表】*/
		Result result = new Result();
		if (backMemberDetailVo == null || backMemberDetailVo.getMemberId() == null || backMemberDetailVo.getSysId() == null) {
			// 参数错误
			result.setErrorCode(ErrorCode.PARAM_ABSENT);
			result.setMessage("necessary paramer absent");
			return result;
		}
		
		Member existMember = memberMapper.findById(backMemberDetailVo.getMemberId());
		if (existMember == null) {
			// 会员不存在
			result.setErrorCode(ErrorCode.MEMBER_NOT_EXIST);
			result.setMessage("member is not exist");
			return result;
		}
		// 查询会员账户信息
		MemberAccount parmMemberAccount = new MemberAccount();
		parmMemberAccount.setMemberId(backMemberDetailVo.getMemberId());
		parmMemberAccount.setSysId(backMemberDetailVo.getSysId());
		MemberAccount oldMemberAccount = memberAccountMapper.findMemberAccount(parmMemberAccount);
		if (oldMemberAccount == null) {
			throw new CustomException(ErrorCode.MEMBER_ACCOUNT_NOT_EXIST.getCode(), "memberAccount is not exist");
		}
		// 判断会员是否被禁用
		if (oldMemberAccount.getStatus().equals(MemberStatus.FREEZE)) {
			result.setErrorCode(ErrorCode.ELSE);
			result.setMessage("该会员已被禁用，无法修改会员信息");
			return result;
		}
		
		// 判断手机是否符合绑定规则(是否其他会员已经绑定)
		if (backMemberDetailVo.getPhone() != null) {
			Member phone = new Member();
			phone.setPhone(backMemberDetailVo.getPhone());
			Member iPhone = memberMapper.findByMember(phone);
			if (iPhone != null && !(backMemberDetailVo.getMemberId().equals(iPhone.getId()))) {
				result.setErrorCode(ErrorCode.PHONE_IS_BINDING);
				result.setMessage("Binding mobile phone number has been bound to another account");
				return result;
			}
		}
		// 修改会员表信息
		memberMapper.updateBack(backMemberDetailVo);
		
		if (oldMemberAccount.getStatus() != null && memberAccountService.filterMemberStatus(oldMemberAccount, null)) {
			throw new CustomException(ErrorCode.MEMBER_IS_FREEZE.getCode(), ErrorCode.MEMBER_IS_FREEZE.getCnMessage());
		}
		
		Long oldMemberId = oldMemberAccount.getMemberLevelId();
		
		// 修改会员等级
		if (!(oldMemberAccount.getMemberLevelId().equals(backMemberDetailVo.getMemberLevelId()))) {
			// 根据(后台返回的)等级ID查询最低成长值
			MemberLevel memberLevel = memberLevelMapper.findById(backMemberDetailVo.getMemberLevelId());
			// 修改成长值和会员等级
			if (memberLevel == null) {
				throw new CustomException(ErrorCode.MEMBER_LEVEL_IS_NULL.getCode(), "memberLevel is null");
			}
			
			// 修改之前的成长值
			Integer oldGrowthValue = oldMemberAccount.getGrowthValue() == null ? 0 : oldMemberAccount.getGrowthValue();
			// 修改之后的成长值
			Integer newGrowthValue = memberLevel.getGrowthValueDown();
			// 记录~
			GrowthValRecord growthValRecord = new GrowthValRecord();
			growthValRecord.setMemberId(oldMemberAccount.getMemberId());
			growthValRecord.setSysId(oldMemberAccount.getSysId());
			growthValRecord.setBeforeGrowthVal(oldGrowthValue);
			growthValRecord.setUpdateId(backMemberDetailVo.getUpdateId());
			growthValRecord.setCreateId(backMemberDetailVo.getUpdateId());
			growthValRecord.setCreateTime(DateUtils.getCurrentDateTime());
			growthValRecord.setUpdateTime(DateUtils.getCurrentDateTime());
			growthValRecord.setDelFlag(ConstantsUtil.DEL_FLAG_NO_0);
			if (newGrowthValue == null) {
				// 设置为代理商 --升级
				// memberAccountMapper.update(memberAccount);
				memberAccountMapper.updateMemberAccountToAgent(oldMemberAccount.getId());
				growthValRecord.setAfterGrowthVal(0);
				growthValRecord.setGrowthValType(GrowthValType.BACK_ADD);
				growthValRecord.setAlterGrowthVal(-1 * (oldGrowthValue));
				growthValRecord.setRemark("调整会员等级");
				growthValRecordMapper.insert(growthValRecord);
			} else {
				
				Integer modityGrowthValue = (newGrowthValue.intValue()) - (oldGrowthValue.intValue());
				// 修改成长值和等级
				memberAccountMapper.updateGrowthValueAndLevel(oldMemberAccount.getId(), modityGrowthValue, backMemberDetailVo.getMemberLevelId());
				growthValRecord.setAfterGrowthVal(newGrowthValue);
				growthValRecord.setAlterGrowthVal(modityGrowthValue);
				
				if (MemberLevel.AGENT_MEMBER_LEVEL_ID.equals(oldMemberId)) {
					// 代理商变成会员降级
					growthValRecord.setGrowthValType(GrowthValType.BACK_REMOVE);
				} else if (modityGrowthValue.intValue() < 0) {
					growthValRecord.setGrowthValType(GrowthValType.BACK_REMOVE);
					// growthValRecord.setRemark(GrowthValType.BACK_REMOVE.getName());
				} else {
					growthValRecord.setGrowthValType(GrowthValType.BACK_ADD);
					// growthValRecord.setRemark(GrowthValType.BACK_ADD.getName());
				}
				growthValRecord.setRemark("调整会员等级");
				// if (modityGrowthValue.intValue() != 0) { 0要求要保存
				growthValRecordMapper.insert(growthValRecord);
				// }
				
			}
			
			// -------------------------------------------------------
		}
		
		// 修改会员收获地址信息
		if (backMemberDetailVo.getBackDeliveryAddressVo() != null && backMemberDetailVo.getBackDeliveryAddressVo().size() > 0) {
			List<BackDeliveryAddressVo> backDeliveryAddress = backMemberDetailVo.getBackDeliveryAddressVo();
			
			boolean flag = false;
			DeliveryAddress defaultAddress = null;
			Map<Long, Object> addressMap = new HashMap<>();
			for (BackDeliveryAddressVo address : backDeliveryAddress) {
				
				if (address.getDelFlag() == null) {
					address.setDelFlag(ConstantsUtil.DEL_FLAG_NO_0);
				}
				
				if (address.getIsDefault() == null) {
					address.setDelFlag(DeliveryAddress.IS_DEFUALT_NO_0);
				}
				
				// 判断手机或者电话是否存在一个 并且符合格式
				boolean isPhoneNotNull = validateMobilePhoneAndPhone(address.getMobilePhone(), address.getPhone());
				if (!isPhoneNotNull) {
					// 必需：手机或电话必填一个 且符合格式
					throw new CustomException(ErrorCode.ILLEGAL_PARAM.getCode(), "手机或电话必填一个 且符合格式");
				}
				
				// 已经有默认收货地址，后面的地址将被改成非默认
				if (flag && DeliveryAddress.IS_DEFUALT_YES_1 == address.getIsDefault()) {
					address.setIsDefault(DeliveryAddress.IS_DEFUALT_NO_0);
				}
				
				// DeliveryAddress parm = deliveryAddressMapper.findById(address.getId());
				// if (parm != null) {
				if (address.getId() != null) {
					// 修改收货地址 或者 删除
					address.setMemberId(backMemberDetailVo.getMemberId());
					address.setSysId(backMemberDetailVo.getSysId());
					// 修改(如果有字段是null 数据库也要为空)-【邮箱】 【手机号/固话】二选一
					
					deliveryAddressMapper.updateDeliveryAddressBack(address);
					if (defaultAddress == null) {
						DeliveryAddress newDeliveryAddress = new DeliveryAddress();
						newDeliveryAddress.setId(address.getId());
						defaultAddress = newDeliveryAddress;
					}
					addressMap.put(address.getId(), null);
				} else {
					// 新增收货地址
					DeliveryAddress newDeliveryAddress = new DeliveryAddress();
					BeanUtils.copyProperties(address, newDeliveryAddress);
					newDeliveryAddress.setMemberId(backMemberDetailVo.getMemberId());
					newDeliveryAddress.setSysId(backMemberDetailVo.getSysId());
					newDeliveryAddress.setCreateTime(DateUtils.getCurrentDateTime());
					newDeliveryAddress.setUpdateTime(DateUtils.getCurrentDateTime());
					newDeliveryAddress.setDelFlag(address.getDelFlag());
					deliveryAddressMapper.insert(newDeliveryAddress);
					if (defaultAddress == null) {
						defaultAddress = newDeliveryAddress;
					}
					addressMap.put(newDeliveryAddress.getId(), null);
				}
				if (!flag && address.getIsDefault().equals(DeliveryAddress.IS_DEFUALT_YES_1) && address.getDelFlag().equals(BackDeliveryAddressVo.NO_DELFLAG)) {
					// 是否存在默认地址
					flag = true;
				}
				
				if (!flag && ConstantsUtil.DEL_FLAG_NO_0 == address.getDelFlag()) {
					// 是否存在默认地址
					flag = false;
				}
				
			}
			// 查询收货地址列表
			List<DeliveryAddress> memberAddressList = deliveryAddressMapper.findByMemberIdAndSysId(backMemberDetailVo.getMemberId(), backMemberDetailVo.getSysId());
			
			// 删除后台没有传对应Id过来的地址
			if (memberAddressList != null && memberAddressList.size() > 0) {
				
				for (DeliveryAddress address : memberAddressList) {
					if (!addressMap.containsKey(address.getId())) {
						address.setDelFlag(ConstantsUtil.DEL_FLAG_YES_1);
						deliveryAddressMapper.update(address);
					}
				}
			}
			
			if (!flag && defaultAddress != null) {
				// 不存在默认收货地址~将第一个设置为默认
				defaultAddress.setIsDefault(DeliveryAddress.IS_DEFUALT_YES_1);
				defaultAddress.setUpdateTime(DateUtils.getCurrentDateTime());
				deliveryAddressMapper.update(defaultAddress);
			}
		}
		/*// 收货地址为空
		throw new CustomException(ErrorCode.NO_SHIPPING_ADDRESS.getCode(), "there is no shipping address");*/
		result.setErrorCode(ErrorCode.SUCCESS);
		return result;
		
	}
	
	private boolean validateMobilePhoneAndPhone(String mobilePhone, String phone) {
		// 手机不能等于空且符合手机格式，或者电话不为空且符合电话格式
		// 同时为空
		if ((StringUtil.isBlank(mobilePhone)) && (StringUtil.isBlank(phone))) {
			return false;
		}
		if (StringUtil.isNotBlank(mobilePhone)) {
			// 不符合格式
			if (!RegexUtils.isMobileFuzzy(mobilePhone)) {
				return false;
			}
		}
		if (StringUtil.isNotBlank(phone)) {
			// 不符合格式
			if (!RegexUtils.isTelePhone(phone)) {
				return false;
			}
		}
		
		return true;
	}
	
	/**
	 * (后台)禁用/启用 会员－未激活的用户要先启用才能禁用
	 * @param memberId
	 * @param sysId
	 * @param status
	 * @return
	 */
	public Result modityMemberStatus(Long memberId, Long sysId, String status, Long updateId) {
		// 'INACTIVE','ACTIVE','FREEZE','WAIT_AUDIT','AUDIT_NO_PASS'状态：'未激活','已激活','已冻结','待审核','审核未通过'
		Result result = new Result();
		// 查询会员现在状态
		MemberAccount parm = new MemberAccount();
		parm.setMemberId(memberId);
		parm.setSysId(sysId);
		MemberAccount oldMemberAccount = memberAccountMapper.findMemberAccount(parm);
		if (oldMemberAccount != null) {
			if (MemberStatus.ACTIVE.toString().equals(status)
					&& (MemberStatus.FREEZE.equals(oldMemberAccount.getStatus()) || MemberStatus.INACTIVE.equals(oldMemberAccount.getStatus()))) {
				// 启用会员
				parm.setStatus(MemberStatus.ACTIVE);
				parm.setId(oldMemberAccount.getId());
				parm.setUpdateId(updateId);
				parm.setUpdateTime(DateUtils.getCurrentDateTime());
				memberAccountMapper.update(parm);
				
				result.setErrorCode(ErrorCode.SUCCESS);
				result.setMessage("会员" + memberId + "已经启用");
				return result;
			} else if (MemberStatus.FREEZE.toString().equals(status) && MemberStatus.ACTIVE.equals(oldMemberAccount.getStatus())) {
				// 禁用会员
				parm.setStatus(MemberStatus.FREEZE);
				parm.setId(oldMemberAccount.getId());
				parm.setUpdateId(updateId);
				parm.setUpdateTime(DateUtils.getCurrentDateTime());
				parm.setDisableTime(DateUtils.getCurrentDateTime());
				memberAccountMapper.update(parm);
				
				result.setErrorCode(ErrorCode.SUCCESS);
				result.setMessage("会员" + memberId + "已经禁用");
				return result;
			}
		} else {
			// 没有查询到该会员
			result.setErrorCode(ErrorCode.NOT_FIND);
			result.setMessage("没有查询到该会员");
			return result;
		}
		// 当前状态无法启用/或者禁用
		result.setErrorCode(ErrorCode.STATE_INVALID);
		result.setMessage(" 当前状态无法启用/或者禁用");
		return result;
	}
	
	/**
	 * (后台)修改会员积分/余额
	 * @param memberId
	 * @param sysId
	 * @param integralOrBalance
	 * @param number
	 * @param remarks
	 * @return
	 * @throws CustomException 
	 */
	
	@Transactional(rollbackFor = Exception.class)
	public Result modifyMemberIntegralOrBalance(Long memberId, Long sysId, String integralOrBalance, BigDecimal number, String remarks, Long updateId) throws CustomException {
		// `TOTAL_AMOUNT` decimal(20,2) NOT NULL DEFAULT '0.00' COMMENT '可用余额',
		// `TOTAL_INTEGRAL` int(11) NOT NULL DEFAULT '0' COMMENT '可用积分数',
		Result result = new Result();
		if (number == null) {
			result.setErrorCode(ErrorCode.PARAM_ABSENT);
			result.setMessage("请输入调整值");
			return result;
		}
		if (remarks == null) {
			result.setErrorCode(ErrorCode.PARAM_ABSENT);
			result.setMessage("请输入备注");
			return result;
		}
		
		Member member = memberMapper.findById(memberId);
		if (member == null) {
			// 会员ID错误 会员不存在
			result.setErrorCode(ErrorCode.MEMBER_NOT_EXIST);
			result.setMessage("会员不存在");
			return result;
		}
		
		MemberAccount parm = new MemberAccount();
		parm.setMemberId(memberId);
		parm.setSysId(sysId);
		MemberAccount memberAccount = memberAccountMapper.findMemberAccount(parm);
		if (memberAccount == null) {
			// 会员信息不存在
			result.setErrorCode(ErrorCode.MEMBER_ACCOUNT_NOT_EXIST);
			result.setMessage("会员信息不存在");
			return result;
		}
		if (MemberStatus.FREEZE.equals(memberAccount.getStatus())) {
			//
			result.setErrorCode(ErrorCode.ELSE);
			result.setMessage("该会员已被禁用，无法调整会员积分/账户余额");
			return result;
		}
		
		if (memberAccountService.filterMemberStatus(memberAccount, result)) {
			return result;
		}
		
		if (IntegralOrBalance.INTEGRAL.toString().equals(integralOrBalance)) {
			/*// 修改之前的积分
			Integer beforeIntegral = memberAccount.getTotalIntegral();
			// 修改的积分
			Integer modityIntegral = number.intValue();
			// 修改之后的积分
			Integer afterIntegral = beforeIntegral + modityIntegral;
			if (afterIntegral.intValue() < 0) {
				afterIntegral = new Integer(IntegralRecord.MIN_VALUE);
				modityIntegral = new Integer(afterIntegral.intValue() - beforeIntegral.intValue());
			}
			memberAccount.setTotalIntegral(afterIntegral);
			memberAccountMapper.updateIntegral(memberAccount.getId(), modityIntegral);
			
			// 记录~
			IntegralRecord integralRecord = new IntegralRecord();
			integralRecord.setMemberId(memberId);
			integralRecord.setSysId(sysId);
			integralRecord.setBeforePoint(beforeIntegral);
			integralRecord.setAfterPoint(afterIntegral);
			integralRecord.setAlterPoint(modityIntegral);
			integralRecord.setIntegralType(IntegralType.OTHERS);
			integralRecord.setUpdateId(updateId);
			integralRecord.setRemark(remarks);
			integralRecordService.insert(integralRecord);*/
			Integer modityIntegral = 0;
			if (number != null) {
				// 修改的积分
				modityIntegral = number.intValue();
			}
			
			integralRecordService.addIntegralRecord(memberId, sysId, updateId, updateId, modityIntegral, IntegralType.BACK_ALTER, remarks, null, null, IntegralRecord.IS_BUY_NO);
			
		} else if (IntegralOrBalance.BALANCE.toString().equals(integralOrBalance)) {
			// 修改之前的余额
			BigDecimal beforeBalance = memberAccount.getTotalAmount();
			// 修改的余额
			BigDecimal modityBalance = number;
			// 修改之后的余额
			BigDecimal afterBalance = beforeBalance.add(modityBalance);
			int r = afterBalance.compareTo(BigDecimal.ZERO);
			if (r == NEGATIVE_NUMBER) {
				afterBalance = new BigDecimal(BalanceRecord.MIN_VALUE);
				modityBalance = afterBalance.subtract(beforeBalance);
			}
			memberAccount.setTotalAmount(afterBalance);
			memberAccountMapper.updateAmount(memberAccount.getId(), modityBalance);
			
			// 记录~
			BalanceRecord balanceRecord = new BalanceRecord();
			balanceRecord.setMemberId(memberId);
			balanceRecord.setSysId(sysId);
			balanceRecord.setBeforeMoney(beforeBalance);
			balanceRecord.setAfterMoney(afterBalance);
			balanceRecord.setAlterMoney(modityBalance);
			balanceRecord.setBalanceType(BalanceType.BACK_ALTER);
			balanceRecord.setUpdateId(updateId);
			balanceRecord.setRemark(remarks);
			balanceRecordService.insert(balanceRecord);
		} else {
			result.setErrorCode(ErrorCode.PARAM_ABSENT);
			return result;
		}
		result.setErrorCode(ErrorCode.SUCCESS);
		result.setMessage("修改成功");
		return result;
	}
	
}
